/**
 * 此文件用于会议室页数据管理
 */
import { quickConference, getCfPwd, updatePassword } from '@/api/conference'
import tools from '@/utils/tools'
import { sendSock } from '@/utils/socketSend'

const oldState = {
  // 当前会议类型 videoCall: 视频通话，conferenceRoom: 多人会议
  cf_type: null,
  // 入会前设置
  conferenceSettings: {},
  // 当前会议ID
  cf_id: null,
  // 当前会议号
  cf_code: null,
  // 当前会议名称
  cf_name: null,
  // 当前会议主持人
  cf_host: null,
  // 当前会议发起人
  cf_sponsor: null,
  // 当前会议时间
  cf_start_time: null,
  // 当前会议入会密码
  cf_password: null,
  // 当前会议在会人员
  cf_members: [],
  // 当前会议邀请人员
  cf_invited: [],
  // 当前会议是否静音所有成员
  cf_mute_all: null,
  // 当前会议是否锁定
  cf_isLocked: false,
  // 当前会议是否开启会议密码
  cf_need_password: false,
  // 会议聊天内容
  cf_chatContent: [],
  // 全屏的用户ID
  cf_fullScreen_id: null,
  // 会议通知弹窗的类型 type: 1.被设置为主持人 2.主持人已经结束会议 3.被踢出会议
  cf_notification: null,
  // 主持人解除静音的弹窗
  cf_relieve: false,
  // 当前音频输入设备ID
  audioInputId: null,
  // 当前视频输入设备ID
  videoInputId: null,
  // 音频输入设备列表
  audioInputList: [],
  // 视频输入设备列表
  videoInputList: [],
  // 判断用户是否更换过输入设备
  ifChangeInput: false
}

const state = JSON.parse(JSON.stringify(oldState))

const getters = {
  // 排序之后的会议成员列表
  cf_members (state) {
    const hostList = state.cf_members.filter(item => item.id === state.cf_host)
    const memberList = state.cf_members.filter(item => item.id !== state.cf_host)
    return [...hostList, ...memberList]
  }
}

const mutations = {
  // 重置state
  reset_state (state) {
    for (const key in state) {
      state[key] = oldState[key]
    }
  },
  // 批量设置会议某状态
  set_attribute (state, { attributeKey, attributeValue }) {
    if (Object.keys(state).some(item => item === attributeKey)) {
      state[attributeKey] = attributeValue
    }
  },
  // 添加/重置聊天内容
  set_cf_chatContent (state, { list, type }) {
    if (type === 'set') {
      state.cf_chatContent = list
    } else {
      const oldList = JSON.parse(JSON.stringify(state.cf_chatContent))
      list.forEach(item => {
        if (!oldList.some(it => item.msgID === it.msgID)) {
          oldList.push(item)
        }
      })
      state.cf_chatContent = oldList
    }
  },
  // 设置当前会议类型
  set_cf_type (state, cfType) {
    state.cf_type = cfType
  },
  // 设置当前会议设置
  set_conferenceSettings (state, settings) {
    state.conferenceSettings = JSON.parse(JSON.stringify(settings))
  },
  // 设置当前会议—操作自己的麦克风
  set_conferenceSettings_voiced (state, bool) {
    state.conferenceSettings.voiced = bool
  },
  // 设置当前会议-操作自己的摄像头
  set_conferenceSettings_camera (state, bool) {
    state.conferenceSettings.camera = bool
  },
  // 设置当前会议-操作自己是否显示参会时长
  set_conferenceSettings_durationOfAttendance (state, bool) {
    state.conferenceSettings.durationOfAttendance = bool
  },
  // 设置当前会议ID
  set_cf_id (state, cfID) {
    state.cf_id = cfID
  },
  // 设置当前会议号
  set_cf_code (state, cfCode) {
    state.cf_code = cfCode
  },
  // 设置当前会议名称
  set_cf_name (state, cfName) {
    state.cf_name = cfName
  },
  // 设置当前会议主持人
  set_cf_host (state, cfHost) {
    state.cf_host = cfHost
  },
  // 设置当前会议发起人
  set_cf_sponsor (state, cfSponsor) {
    state.cf_sponsor = cfSponsor
  },
  // 设置当前会议时间
  set_cf_start_time (state, cfStartTime) {
    state.cf_start_time = cfStartTime
  },
  // 设置当前会议密码
  set_cf_password (state, cfPassword) {
    state.cf_password = cfPassword
  },
  // 设置当前会议是否静音所有成员
  set_cf_mute_all (state, bool) {
    state.cf_mute_all = bool
  },
  // 设置当前会议是否锁定
  set_cf_isLocked (state, bool) {
    state.cf_isLocked = bool
  },
  // 设置当前会议是否开启入会密码
  set_cf_need_password (state, bool) {
    state.cf_need_password = bool
  },
  // 设置当前会议在会人员
  set_cf_members (state, cfMembers) {
    state.cf_members = cfMembers
  },
  // 设置当前会议在会人员-添加在会人员
  add_cf_member (state, userInfo) {
    state.cf_members.push(userInfo)
  },
  // 设置当前会议成员-修改摄像头或者麦克风状态
  set_cf_member_device (state, { id, type, status }) {
    state.cf_members.forEach(item => {
      if (item.id === id) {
        item[type] = status
      }
    })
  },
  // 设置未入会人员数组
  set_cf_invited (state, list) {
    state.cf_invited = list
  },
  // 添加未入会人员
  add_cf_invited (state, user) {
    state.cf_invited.push(user)
  },
  // 剔除未入会人员
  delete_cf_invited (state, id) {
    state.cf_invited = state.cf_invited.filter(item => item.id !== id)
  },
  // 设置当前会议自己-添加自己的媒体流
  add_selfStream (state, stream) {
    state.cf_members.forEach(item => {
      if (tools.isSelf(item.id)) {
        item.stream = stream
      }
    })
  },
  // 设置当前会议在会人员-添加一条新的媒体轨道
  add_track (state, { id, track }) {
    state.cf_members.forEach(item => {
      if (item.id === id) {
        item.stream.addTrack(track)
      }
    })
  },
  // 设置当前会议在会人员-添加一条新的peer
  add_peer (state, { id, peer }) {
    state.cf_members.forEach(item => {
      if (item.id === id) {
        item.peer = peer
      }
    })
  },
  // 设置当前会议在会人员-添加ice候选
  add_iceCandidate (state, { id, sdpMid, sdpMLineIndex, candidate }) {
    state.cf_members.forEach(item => {
      if (item.id === id) {
        tools.webRTC.addIceCandidate(item.peer, sdpMid, sdpMLineIndex, candidate)
      }
    })
  },
  // 设置当前会议人员-关闭一条peer通道
  close_peer (state, id) {
    state.cf_members.forEach(item => {
      if (item.id === id) {
        item.peer.close()
        item.peer = null
      }
    })
  },
  // 设置当前会议人员-关闭所有peer通道
  close_allPeer (state) {
    state.cf_members.forEach(item => {
      if (item.peer) {
        item.peer.close()
      }
    })
  },
  // 为当前用户设置新的媒体流
  reset_mediaStream (state, id) {
    state.cf_members.forEach(item => {
      if (item.id === id) {
        item.stream = new MediaStream()
      }
    })
  },
  // 剔除一名会议成员
  remove_member (state, id) {
    state.cf_members = state.cf_members.filter(item => item.id !== id)
  },
  // 设置全屏的用户ID 并且将id为fullScreenBox的盒子全屏
  set_fullScreen_id (state, id) {
    state.cf_fullScreen_id = id
  },
  // 设置会议通知内容的消息文本
  set_cf_notification (state, notification) {
    state.cf_notification = notification
  },
  // 设置主持人解除静音弹窗的显示/隐藏
  set_cf_relieve (state, bool) {
    state.cf_relieve = bool
  },
  // 设置当前输入设备ID
  set_deviceId (state, { type, id }) {
    if (type === 'audio') {
      state.audioInputId = id
    } else if (type === 'video') {
      state.videoInputId = id
    }
  },
  // 设置输入设备列表
  set_deviceInputList (state, { type, list }) {
    if (type === 'audioinput') {
      state.audioInputList = list
    } else if (type === 'videoinput') {
      state.videoInputList = list
    }
  },
  // 设置判断用户是否切换输入设备
  set_ifChangeInput (state, bool) {
    state.ifChangeInput = bool
  }
}

const actions = {
  // 快速会议
  createQuickConference ({ rootState, state, commit }, { cfName, cfPwd }) {
    return new Promise((resolve, reject) => {
      quickConference({ cfName, cfPwd }).then(res => {
        if (res.data && res.data.code === 200) {
          // 将常规设置继承给当前会议
          commit('set_conferenceSettings', rootState.user.generalSettings)
          // 发送加入会议消息
          sendSock({
            type: '4.1.1',
            body: {
              voiced: state.conferenceSettings.voiced,
              camera: state.conferenceSettings.camera,
              cf_join_type: 0,
              cf_id: res.data.data.cf_id,
              cf_pwd: cfPwd || ''
            }
          })
          commit('socket/set_operationReqId', 'joinConferenceReqId', { root: true })
          if (cfPwd) {
            commit('set_cf_password', cfPwd)
          }
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 根据会议ID取会议密码
  getPassword ({ state }) {
    return new Promise((resolve, reject) => {
      getCfPwd(state.cf_id).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 更新会议密码
  updateCfPwd ({ state, commit }, { cfNeedPassword, cfPassword }) {
    return new Promise((resolve, reject) => {
      updatePassword(state.cf_id, cfNeedPassword, cfPassword).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
